#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "exif.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QDir>
#include <QImageReader>
#include <QDateTime>
#include <string.h>
#include <libexif/exif-data.h>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_exit_Button_clicked()
{

    int result = QMessageBox::question(this, "退出确认", "确定退出吗?",
                                       QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
    if (result == QMessageBox::Yes) {
        QApplication::quit();
    }

}

void MainWindow::on_Directory_Button_clicked()
{
    QString dirName = QFileDialog::getExistingDirectory(
        this,
        tr("选择目录"),
        ""
    );

    if (!dirName.isEmpty()) {
            // 确保你的 Ui::MainWindow 类中包含了指向 Dirctory_TextEdit 的指针
            ui->Dirctory_TextEdit->setPlainText(dirName);
        }
}

void MainWindow::on_Files_Count_clicked()
{
    // 获取 QPlainTextEdit 中的目录路径字符串
    QString dirPath = ui->Dirctory_TextEdit->toPlainText().trimmed();

    // 检查字符串是否有效
    if (dirPath.isEmpty()) {
        // 如果目录路径为空，可以显示错误消息或日志
        QMessageBox::information(this, "文件统计结果", "目录为空");
        return;
    }

    // 使用字符串构造 QDir 对象
    QDir rootDir(dirPath);

    // 确保目录存在
    if (!rootDir.exists()) {
        // 如果目录不存在，可以显示错误消息或日志
        QMessageBox::information(this, "文件统计结果", "目录无效！");
        return;
    }

    // 计算文件总数
    int totalFiles = countFilesInDirectory(rootDir);

    // 使用 QMessageBox 显示文件总数
    QMessageBox::information(this, "文件统计结果",
                             QString("目录 %1 及其子目录中共有 %2 个文件。").arg(dirPath, QString::number(totalFiles)));
}

int MainWindow::countFilesInDirectory(const QDir &directory)
{
    int fileCount = 0;

    QFileInfoList entries = directory.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries);
    for (const QFileInfo &info : entries) {
        if (info.isDir()) {
            // 递归进入子目录
            QDir subDir(info.absoluteFilePath());
            fileCount += countFilesInDirectory(subDir);
        } else if (info.isFile()) {
            // 如果是文件，增加文件计数
            ++fileCount;
        }
    }
    return fileCount;
}

void MainWindow::on_File_Button_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, "选择文件", "", "所有文件 (*)");

    // 检查用户是否选择了文件
    if (!fileName.isEmpty())
    {
        // 将文件名设置到 QPlainTextEdit 控件中
        ui->File_TextEdit->setPlainText(fileName);
    }
}

void MainWindow::on_FileAttr_Button_clicked()
{
    QString  str = getImageDateTime(ui->File_TextEdit->toPlainText().trimmed());

    QMessageBox::information(this, "提示", str);
}

void MainWindow::trim_spaces(char *buf)
{
    char *s = buf-1;
    for (; *buf; ++buf) {
        if (*buf != ' ')
            s = buf;
    }
    *++s = 0; /* nul terminate the string on the first of the final spaces */
    return;
}

QString MainWindow::getImageDateTime(const QString& filePath) {
    QString  attrStr = "23";
    char     buf[1024];

    ExifData  *ed;
    ExifEntry *entry;

    /* Load an ExifData object from an EXIF file */
    ed = exif_data_new_from_file(filePath.toUtf8().data());

    if((!ed) || (!ed->ifd[EXIF_IFD_EXIF])){
        attrStr = "No shooting time";
        return attrStr;
    }

    entry = exif_content_get_entry(ed->ifd[EXIF_IFD_EXIF],
        EXIF_TAG_DATE_TIME_DIGITIZED);
    if(!entry){
       attrStr = "No shooting time";
       return attrStr;
    }


    /* Get the contents of the tag in human-readable form */
    exif_entry_get_value(entry, buf, sizeof(buf));

    /* Don't bother printing it if it's entirely blank */
    trim_spaces(buf);
    attrStr =  QString::fromUtf8(buf);
    return attrStr;

    if (*buf) {
        printf("%s\n", buf);
    }

#if 0
    if (file.open(QIODevice::ReadOnly)){
                QByteArray data = file.readAll();
                easyexif::EXIFInfo info;
                if (int code = info.parseFrom((unsigned char *)data.data(), data.size())){
                    return "Error parsing EXIF: code ";
                }
                //qDebug() << "Camera model         : " << info.Model.c_str();
                return info.DateTimeOriginal.c_str();
            } else
                return ("Can't open file:");

        QImageReader reader(filePath);


        reader.setFormat("JPG"); // 或者使用 reader.format() 如果你知道文件的格式

        const QImage newImage = reader.read();

        reader.

        // 尝试读取 Exif.Image.DateTimeOriginal 和 Exif.Photo.DateTimeOriginal
        QByteArray key1 = "Exif.Image.DateTimeOriginal";
        QByteArray key2 = "Exif.Photo.DateTimeOriginal";

        QString dateTimeStr;
        if (!reader.text(key1).isEmpty()) {
            dateTimeStr = reader.text(key1);
        } else if (!reader.text(key2).isEmpty()) {
            dateTimeStr = reader.text(key2);
        }

        if (!dateTimeStr.isEmpty()) {
            // 解析日期时间字符串，格式应该是 "YYYY:MM:DD HH:MM:SS"
            QDateTime dateTime = QDateTime::fromString(dateTimeStr, "yyyy:MM:dd hh:mm:ss");
            return dateTime.toString(Qt::SystemLocaleShortDate);
        } else {
            return "未知==3333";
        }
#endif
}
